package com.cqw.auth.config.handler;

import com.cqw.auth.config.RedisClient;
import com.cqw.auth.enums.CodeEnum;
import com.cqw.auth.utils.JwtTokenUtil;
import com.cqw.auth.utils.ResultJSON;
import com.cqw.auth.utils.SecurityHandlerUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 注销成功
 * @Author cqw
 * @Date 2020年12月31日15:08:47
 */
public class LogoutHandlerImpl implements LogoutSuccessHandler {


    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(httpServletRequest.getServletContext());
        String tokenHeader = httpServletRequest.getHeader(JwtTokenUtil.TOKEN_HEADER);
        // 去掉前缀 获取Token字符串
        String token = tokenHeader.replace(JwtTokenUtil.TOKEN_PREFIX, "");
        // 从Token中解密获取用户名
        String username = JwtTokenUtil.getUsername(token);
        // 从Token中解密获取用户角色
        String role = JwtTokenUtil.getUserRole(token);
        RedisClient redisClient = wac.getBean(RedisClient.class);
        redisClient.delete(JwtTokenUtil.REDIS_TOKEN + username + role);
        SecurityHandlerUtil.responseHandler(httpServletResponse,new ResultJSON(CodeEnum.LOGOUT_SUCCESS));
    }
}
